package com.module.framework.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.module.framework.constants.SystemConstants;
import com.module.framework.domain.*;
import com.module.framework.dto.BookListDTO;
import com.module.framework.mapper.BookMapper;
import com.module.framework.mapper.NowLendMapper;
import com.module.framework.mapper.UserMapper;
import com.module.framework.service.BookService;
import com.module.framework.service.CategoryService;
import com.module.framework.utils.BeanCopyUtils;
import com.module.framework.vo.BookDetailVO;
import com.module.framework.vo.PageVO;
import com.module.framework.vo.ProductDetailVO;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Service
public class BookServiceImpl extends ServiceImpl<BookMapper, Book> implements BookService {

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private BookMapper bookMapper;

    @Autowired
    private NowLendMapper nowLendMapper;

    @Autowired
    private UserMapper userMapper;

    @Value("${absoluteImgPath}")
    String absoluteImgPath;

    @Value("${sonImgPath}")
    String sonImgPath;

    @Override
    public PageVO bookList(BookListDTO bookListDTO) {

        Integer pageNum = bookListDTO.getPageNum();
        String name = bookListDTO.getName();
        String author = bookListDTO.getAuthor();
        Integer cateId = bookListDTO.getCateId();
        LambdaQueryWrapper<Book> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(Objects.nonNull(name), Book::getName, name);
        queryWrapper.like(Objects.nonNull(author), Book::getAuthor, author);
        queryWrapper.eq(Objects.nonNull(cateId) && cateId > 0, Book::getCateId, cateId);

        PageVO pageVO = null;
        if (pageNum == null && bookListDTO.getPageSize() == null) {
            List<Book> lists = list(queryWrapper);
            // 查询categoryName
            for (Book list : lists) {
                Category category = categoryService.getById(list.getCateId());
                list.setCategoryName(category.getName());
            }
            List<BookListDTO> bookListDTOS = BeanCopyUtils.copyBeanList(lists, BookListDTO.class);
            pageVO = new PageVO(bookListDTOS, bookListDTOS.size());
        } else {
            //分页查询
            Integer pageSize = bookListDTO.getPageSize() == null ? SystemConstants.PAGE_SIZE : bookListDTO.getPageSize();
            Page<Book> page = new Page<>(pageNum, pageSize);
            page(page, queryWrapper);

            // 查询categoryName
            List<Book> records = page.getRecords();
            for (Book record : records) {
                Category category = categoryService.getById(record.getCateId());
                record.setCategoryName(category.getName());
                // 图片完整路径
                record.setPicture(absoluteImgPath + record.getPicture());
            }
            // bean拷贝
            List<Book> bookVo = BeanCopyUtils.copyBeanList(page.getRecords(), Book.class);
            pageVO = new PageVO(bookVo, (int) page.getTotal());

        }
        return pageVO;
    }

    @Override
    public void addBook(MultipartFile file, String data) {
        // json转为实体类，先转成JSON对象，JSON对象转换成Java对象
        JSONObject jsonObject = JSONObject.parseObject(data);
        Book getBook = JSONObject.toJavaObject(jsonObject, Book.class);
        Book book = BeanCopyUtils.copyBean(getBook, Book.class);

        if (file != null) {
            // 获取文件名称
            String fileName = file.getOriginalFilename();
            // 获取文件名后缀
            String suffix = fileName.substring(file.getOriginalFilename().lastIndexOf("."));
            suffix = suffix.toLowerCase();
            // 随机生成文件名
            fileName = UUID.randomUUID().toString() + suffix;
            String imgUrl = sonImgPath + fileName;
            book.setPicture(imgUrl);

            //将上传文件保存到一个目标文档中
            Map<String, String> map = new HashMap<>();
            File dest = new File(absoluteImgPath + fileName);
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            try {
                file.transferTo(dest);
                map.put("res", "success");
                map.put("url", fileName);
            } catch (IOException e) {
                map.put("res", "error");
            }
        }
        bookMapper.insert(book);
    }

    @Override
    public BookDetailVO getBookInfo(Integer id) {
        //根据id查询产品信息
        Book book = getById(id);
        BookDetailVO bookDetailVO = BeanCopyUtils.copyBean(book, BookDetailVO.class);
        //根据分类id查询分类信息
        Integer cateId = book.getCateId();
        Category category = categoryService.getById(cateId);
        if (category != null) {
            bookDetailVO.setCategoryName(category.getName());
        }
        if (book.getPicture() != null) {
            bookDetailVO.setPicture(book.getPicture());
        }
        return bookDetailVO;
    }

    @Override
    public void updateBook(Book book) {
        bookMapper.updateById(book);
    }

    @Override
    public void deleteBook(Integer id) {
        bookMapper.deleteById(id);
    }

    @Override
    public String lendBook(Integer id, Long userId) {
        Book book = getById(id);
        if (book.getStatus() == 0 && book.getSpareNumber() > 0) {

            User user = userMapper.selectById(userId);
            Integer lendNum = user.getLendNumber();
            if (lendNum < 5 && user.getBan() == 0) {
                user.setLendNumber(lendNum + 1);
                userMapper.updateById(user);

                Integer num = book.getSpareNumber() - 1;
                book.setSpareNumber(num);
                bookMapper.updateById(book);


                SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Calendar c = Calendar.getInstance();
                c.add(Calendar.DATE, 30);
                String str2 = s.format(c.getTime());
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                LocalDateTime dateTime = LocalDateTime.parse(str2, formatter);
                long milleSecond = dateTime.toInstant(ZoneOffset.of("+8")).toEpochMilli();

                // 插入到借阅表中一条信息  todo
                NowLend nowLend = new NowLend();
                nowLend.setBookId(book.getId());
                nowLend.setUserId(userId);
                nowLend.setDeadline(new Date(milleSecond));
                nowLendMapper.insert(nowLend);
                return "借阅成功";
            } else {
                return "该用户借书逾期或者已借图书到达最大上限5";
            }
        } else {
            return "此图书不允许借阅或图书库存量不足";
        }
    }

}
